package com.nus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.params.HttpConnectionParams;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.nus.parsers.ParserAPIs;
import com.nus.representations.IvleNews;
import com.nus.representations.IvleStudentEvents;
public class IvleStudentEventActivity extends Activity implements OnClickListener  {
	private ListView lv;
	private ListView listview;
	private String lv_arr[];
	public static ArrayList<IvleStudentEvents> sevents;
	//static variables which store details of each event
	public static String Student_Event_Id;
	public static String Student_Event_Title;
	public static String Student_Event_Agenda;
	public static String Student_Event_Description;
	public static String Student_Event_Contact;
	public static String Student_Event_DateTime;
	public static String Student_Event_Organizer;
	public static String Student_Event_Price;
	public static String Student_Event_Venue;
	public ImageButton home;
	protected TextView title;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.ivlestudentevents);
		 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
		 title = (TextView) findViewById(R.id.titleheader);
		 title.setText("Student Events");
		listview = (ListView) findViewById(R.id.studeventlv);
		//listview.setTextFilterEnabled(true);
		 /*home = (ImageButton) findViewById(R.id.home);
	        home.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					startActivity(new Intent("com.nus.OptionsActivity"));
				}
			});*/
		 ImageView b = (ImageView)findViewById(R.id.home);
		  b.setImageDrawable(getResources().getDrawable(R.drawable.events));
		boolean netconn = checkInternetConnection();
		if(!netconn){
			Toast.makeText(getApplicationContext(), "Please check your internet or 3G connection", Toast.LENGTH_LONG).show();       
        }
		String value = null;
		Bundle extras = getIntent().getExtras();
		if(extras !=null)
		{
			value = extras.getString("IVLE_Token");
		}
		Log.i("Token is",value);
		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/StudentEvents?APIKey=W7RtgW7GZKUpaEkJ1NwUD&AuthToken="+value+"&TitleOnly=false&output=json";
		try {
			String response = getResponseText(url);

			Log.i("ResponseR",response);
			//Experiment = new String[40];
			sevents = ParserAPIs.parseIvleStudentEvents(response);
			listview.setAdapter(new ListAdapter(IvleStudentEventActivity.this, R.id.rlt_main,
					sevents));
			}
	        catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    OptionsActivity.pd.dismiss();
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
// ***ListAdapter***
	
	private class ListAdapter extends ArrayAdapter<IvleStudentEvents> { // --
																// CloneChangeRequired
		private ArrayList<IvleStudentEvents> mstudents; // --CloneChangeRequired
		private Context mContext;
		
		public ListAdapter(Context context, int textViewResourceId,
				ArrayList<IvleStudentEvents> list) { // --CloneChangeRequired
			super(context, textViewResourceId, list);
			this.mstudents = list;
			this.mContext = context;
		}
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		try {
			if (view == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.list_item0, null); 
			}
			final IvleStudentEvents listItem = mstudents.get(position); 
			if (listItem != null) {
				// setting list_item views
				TextView tv =(TextView) view.findViewById(R.id.name);
						tv.setText(listItem.getTitle());
						//tv.setClickable(true);
						//ImageView iv = (ImageView) findViewById(R.id.widget512);
						//iv.setClickable(true);
						//view.setClickable(true);
				view.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) { // --clickOnListItem
						Intent myIntent = new Intent(IvleStudentEventActivity.this,
								IvleStudent_EventDetails_Activity.class);
					   // arg0.setPressed(true);//BackgroundColor(Color.GREEN);
						Student_Event_Id=listItem.getID();
		                Student_Event_Venue=listItem.getVenue();
		            	Student_Event_Title=listItem.getTitle();
		            	Student_Event_Agenda=listItem.getAgenda();
		            	Student_Event_Description=listItem.getDescription();
		            	Student_Event_Contact=listItem.getContact();
		            	Student_Event_DateTime=listItem.getEventDateTime();
		            	Student_Event_Organizer=listItem.getOrganizer();
		            	Student_Event_Price=listItem.getPrice();
		            	Student_Event_Venue=listItem.getVenue();
						startActivity(myIntent);
						//arg0.setBackgroundColor(Color.parseColor("#191919"));
						//finish();
					}
				});
				view.setOnTouchListener(new OnTouchListener() {
					
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
					//	v.setBackgroundColor(Color.BLUE);
						return false;
					}
				});
			}
		} catch (Exception e) {
			Log.i(IvleStudentEventActivity.ListAdapter.class.toString(), e.getMessage());
		}
		return view;
	}
}
	public String getResponseText(String stringUrl) throws IOException
	{
		StringBuilder response  = new StringBuilder();

		URL url = new URL(stringUrl);
		HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
		if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
		{
			BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
			String strLine = null;
			while ((strLine = input.readLine()) != null)
			{
				response.append(strLine);
			}
			input.close();
		}
		return response.toString();
	}
	public boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
            return true;

        } else {
            return false;
        }
    }
}
